package com.carey.myblog.controller.admin;

import com.carey.myblog.pojo.User;
import com.carey.myblog.service.UserService;
import com.carey.myblog.util.MD5;
import com.carey.myblog.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String LoginPage(){
        return "admin/login";
    }

    @PostMapping("login")
    public String Login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes,
                        Model model){
        User user = userService.CheckUser(username, MD5.encrypt(password));
        if (null == user){
            //使用重定向，如果要传参只能使用RedirectAttributes，不能使用Model
            attributes.addFlashAttribute("message","用户名和密码错误");
            return "redirect:/admin";
        }
        user.setPassword(null);
        session.setAttribute("user",user);
        model.addAttribute("index",user);
        return "admin/index";
    }

    @GetMapping("logout")
    public String Logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
